#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
威胁分析系统
从企业舆情分析结果中检测负面内容和数据泄露风险
"""

import asyncio
import aiohttp
import sqlite3
import json
import time
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, field
from enum import Enum


class ThreatType(Enum):
    """威胁类型枚举"""
    NEGATIVE_SENTIMENT = "negative_sentiment"  # 负面情绪
    DATA_LEAK = "data_leak"  # 数据泄露
    REPUTATION_DAMAGE = "reputation_damage"  # 声誉损害
    FINANCIAL_RISK = "financial_risk"  # 财务风险
    LEGAL_RISK = "legal_risk"  # 法律风险
    OPERATIONAL_RISK = "operational_risk"  # 运营风险
    SECURITY_BREACH = "security_breach"  # 安全漏洞
    COMPLIANCE_VIOLATION = "compliance_violation"  # 合规违规
    COMPETITIVE_DISADVANTAGE = "competitive_disadvantage"  # 竞争劣势


class ThreatLevel(Enum):
    """威胁等级枚举"""
    LOW = "low"      # 低风险 (1-3分)
    MEDIUM = "medium"  # 中风险 (4-6分)
    HIGH = "high"     # 高风险 (7-8分)
    CRITICAL = "critical"  # 极高风险 (9-10分)


@dataclass
class ThreatAnalysisResult:
    """威胁分析结果"""
    session_id: str
    question_id: int
    question_text: str
    ai_provider: str
    ai_response: str
    threat_detected: bool
    threat_types: List[ThreatType]
    threat_level: ThreatLevel
    threat_score: float  # 1-10分
    threat_description: str
    recommended_actions: List[str]
    confidence_score: float  # 分析置信度 0-1
    analysis_details: Dict[str, Any]
    analyzed_at: datetime


class ThreatAnalysisDatabase:
    """威胁分析数据库管理器"""
    
    def __init__(self, db_path: str = "enterprise_analysis.db"):
        self.db_path = db_path
        self.init_threat_tables()
    
    def init_threat_tables(self):
        """初始化威胁分析相关表"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # 威胁分析结果表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS threat_analysis (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                question_id INTEGER NOT NULL,
                question_text TEXT NOT NULL,
                ai_provider TEXT NOT NULL,
                ai_response TEXT NOT NULL,
                threat_detected BOOLEAN NOT NULL,
                threat_types TEXT,  -- JSON数组存储威胁类型
                threat_level TEXT NOT NULL,
                threat_score REAL NOT NULL,
                threat_description TEXT,
                recommended_actions TEXT,  -- JSON数组存储建议行动
                confidence_score REAL NOT NULL,
                analysis_details TEXT,  -- JSON存储详细分析信息
                analyzed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # 威胁分析会话表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS threat_analysis_sessions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                analysis_session_id TEXT UNIQUE NOT NULL,
                original_session_id TEXT NOT NULL,
                enterprise_name TEXT NOT NULL,
                total_responses INTEGER DEFAULT 0,
                threats_detected INTEGER DEFAULT 0,
                avg_threat_score REAL DEFAULT 0,
                highest_threat_level TEXT,
                analysis_started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                analysis_completed_at TIMESTAMP,
                status TEXT DEFAULT 'running',
                metadata TEXT
            )
        ''')
        
        # 威胁统计表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS threat_statistics (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                enterprise_name TEXT NOT NULL,
                analysis_date DATE NOT NULL,
                total_threats INTEGER DEFAULT 0,
                critical_threats INTEGER DEFAULT 0,
                high_threats INTEGER DEFAULT 0,
                medium_threats INTEGER DEFAULT 0,
                low_threats INTEGER DEFAULT 0,
                avg_threat_score REAL DEFAULT 0,
                most_common_threat_type TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE(enterprise_name, analysis_date)
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def get_analysis_data(self, session_id: str) -> List[Dict[str, Any]]:
        """获取指定会话的分析数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            cursor.execute('''
                SELECT 
                    q.id as question_id,
                    q.question_text,
                    q.question_type,
                    r.ai_provider,
                    r.response_text,
                    r.success,
                    s.enterprise_name
                FROM questions q
                JOIN ai_responses r ON q.id = r.question_id
                JOIN analysis_sessions s ON q.session_id = s.session_id
                WHERE q.session_id = ? AND r.success = 1 AND r.response_text IS NOT NULL
                ORDER BY q.id
            ''', (session_id,))
            
            columns = [description[0] for description in cursor.description]
            results = []
            for row in cursor.fetchall():
                results.append(dict(zip(columns, row)))
            
            return results
            
        finally:
            conn.close()
    
    def save_threat_analysis_result(self, result: ThreatAnalysisResult) -> int:
        """保存威胁分析结果"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            cursor.execute('''
                INSERT INTO threat_analysis 
                (session_id, question_id, question_text, ai_provider, ai_response, 
                 threat_detected, threat_types, threat_level, threat_score, 
                 threat_description, recommended_actions, confidence_score, analysis_details)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                result.session_id,
                result.question_id,
                result.question_text,
                result.ai_provider,
                result.ai_response,
                result.threat_detected,
                json.dumps([t.value for t in result.threat_types], ensure_ascii=False),
                result.threat_level.value,
                result.threat_score,
                result.threat_description,
                json.dumps(result.recommended_actions, ensure_ascii=False),
                result.confidence_score,
                json.dumps(result.analysis_details, ensure_ascii=False)
            ))
            
            threat_id = cursor.lastrowid
            conn.commit()
            return threat_id
            
        finally:
            conn.close()
    
    def create_threat_analysis_session(self, original_session_id: str, enterprise_name: str) -> str:
        """创建威胁分析会话"""
        analysis_session_id = f"threat_{str(uuid.uuid4())[:8]}"
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            cursor.execute('''
                INSERT INTO threat_analysis_sessions 
                (analysis_session_id, original_session_id, enterprise_name)
                VALUES (?, ?, ?)
            ''', (analysis_session_id, original_session_id, enterprise_name))
            
            conn.commit()
            return analysis_session_id
            
        finally:
            conn.close()
    
    def update_threat_analysis_session(self, analysis_session_id: str, 
                                     total_responses: int = None,
                                     threats_detected: int = None,
                                     avg_threat_score: float = None,
                                     highest_threat_level: str = None,
                                     status: str = None):
        """更新威胁分析会话统计信息"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            updates = []
            params = []
            
            if total_responses is not None:
                updates.append("total_responses = ?")
                params.append(total_responses)
            
            if threats_detected is not None:
                updates.append("threats_detected = ?")
                params.append(threats_detected)
            
            if avg_threat_score is not None:
                updates.append("avg_threat_score = ?")
                params.append(avg_threat_score)
            
            if highest_threat_level is not None:
                updates.append("highest_threat_level = ?")
                params.append(highest_threat_level)
            
            if status is not None:
                updates.append("status = ?")
                params.append(status)
                if status == 'completed':
                    updates.append("analysis_completed_at = CURRENT_TIMESTAMP")
            
            if updates:
                params.append(analysis_session_id)
                cursor.execute(f'''
                    UPDATE threat_analysis_sessions 
                    SET {", ".join(updates)}
                    WHERE analysis_session_id = ?
                ''', params)
                
                conn.commit()
                
        finally:
            conn.close()
    
    def get_threat_summary(self, analysis_session_id: str) -> Dict[str, Any]:
        """获取威胁分析摘要"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            # 获取会话信息
            cursor.execute('''
                SELECT * FROM threat_analysis_sessions 
                WHERE analysis_session_id = ?
            ''', (analysis_session_id,))
            session_data = cursor.fetchone()
            
            if not session_data:
                return {}
            
            # 获取威胁分析结果
            cursor.execute('''
                SELECT threat_level, threat_score, threat_types, threat_description,
                       ai_provider, question_text, threat_detected
                FROM threat_analysis 
                WHERE session_id = ?
                ORDER BY threat_score DESC
            ''', (session_data[2],))  # original_session_id
            
            threat_results = cursor.fetchall()
            
            # 统计威胁等级分布
            level_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
            total_threats = 0
            threat_scores = []
            threat_types_count = {}
            
            for result in threat_results:
                if result[6]:  # threat_detected
                    total_threats += 1
                    level_counts[str(result[0])] += 1  # 确保威胁等级是字符串
                    threat_scores.append(result[1])
                    
                    # 统计威胁类型
                    types = json.loads(result[2]) if result[2] else []
                    for t_type in types:
                        threat_types_count[t_type] = threat_types_count.get(t_type, 0) + 1
            
            avg_score = sum(threat_scores) / len(threat_scores) if threat_scores else 0
            
            return {
                "analysis_session_id": analysis_session_id,
                "original_session_id": session_data[2],
                "enterprise_name": session_data[3],
                "total_responses": session_data[4],
                "threats_detected": total_threats,
                "threat_level_distribution": level_counts,
                "avg_threat_score": avg_score,
                "highest_threat_level": str(session_data[6]) if session_data[6] else "low",  # 确保是字符串
                "most_common_threat_types": threat_types_count,
                "status": session_data[9],
                "analysis_started_at": session_data[7],
                "analysis_completed_at": session_data[8],
                "threat_details": [
                    {
                        "level": str(r[0]), "score": r[1], "types": json.loads(r[2]) if r[2] else [],
                        "description": r[3], "ai_provider": r[4], "question": r[5]
                    } for r in threat_results if r[6]
                ]
            }
            
        finally:
            conn.close()


class DeepSeekThreatAnalyzer:
    """使用DeepSeek进行威胁分析"""
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.deepseek.com/v1"
    
    async def analyze_threat(self, question: str, ai_response: str, 
                           ai_provider: str, enterprise_name: str) -> Dict[str, Any]:
        """分析单个AI响应的威胁等级"""
        timeout = aiohttp.ClientTimeout(total=30)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            try:
                url = f"{self.base_url}/chat/completions"
                headers = {
                    'Authorization': f'Bearer {self.api_key}',
                    'Content-Type': 'application/json'
                }
                
                system_prompt = f"""你是一个专业的企业威胁分析专家。请分析给定的问题和AI回答，评估其中是否包含对企业{enterprise_name}的威胁信息。

请重点关注以下威胁类型：
1. negative_sentiment - 负面情绪和评价
2. data_leak - 数据泄露或隐私问题
3. reputation_damage - 声誉损害
4. financial_risk - 财务风险
5. legal_risk - 法律风险
6. operational_risk - 运营风险
7. security_breach - 安全漏洞
8. compliance_violation - 合规违规
9. competitive_disadvantage - 竞争劣势

请按照以下JSON格式返回分析结果（只返回JSON，不要其他内容）：
{{
    "threat_detected": true/false,
    "threat_types": ["威胁类型1", "威胁类型2"],
    "threat_level": "low/medium/high/critical",
    "threat_score": 分数(1-10),
    "threat_description": "具体威胁描述",
    "recommended_actions": ["建议行动1", "建议行动2"],
    "confidence_score": 置信度(0-1),
    "key_indicators": ["关键指标1", "关键指标2"],
    "severity_factors": ["严重性因素1", "严重性因素2"]
}}

评分标准：
- 1-3分：低风险，轻微负面信息或传言
- 4-6分：中风险，有一定影响的负面信息
- 7-8分：高风险，可能造成重大影响的问题
- 9-10分：极高风险，可能造成严重后果的重大问题"""

                user_prompt = f"""请分析以下内容：

企业名称：{enterprise_name}
AI服务商：{ai_provider}
原始问题：{question}
AI回答：{ai_response}

请评估AI回答中是否包含对该企业的威胁信息。"""

                payload = {
                    "model": "deepseek-chat",
                    "messages": [
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": user_prompt}
                    ],
                    "temperature": 0.2,
                    "max_tokens": 1500
                }
                
                async with session.post(url, json=payload, headers=headers) as response:
                    if response.status == 200:
                        data = await response.json()
                        if 'choices' in data and len(data['choices']) > 0:
                            content = data['choices'][0]['message']['content'].strip()
                            
                            # 尝试解析JSON
                            try:
                                start_idx = content.find('{')
                                end_idx = content.rfind('}') + 1
                                if start_idx != -1 and end_idx != -1:
                                    json_str = content[start_idx:end_idx]
                                    result = json.loads(json_str)
                                    
                                    # 验证和标准化结果
                                    return self._validate_analysis_result(result)
                                    
                            except json.JSONDecodeError:
                                print(f"⚠️ 威胁分析JSON解析失败")
                                
                    else:
                        error_text = await response.text()
                        print(f"DeepSeek威胁分析API错误: {response.status} - {error_text}")
                        
            except Exception as e:
                print(f"威胁分析API调用异常: {e}")
        
        # 如果分析失败，返回默认结果
        return {
            "threat_detected": False,
            "threat_types": [],
            "threat_level": "low",
            "threat_score": 0.0,
            "threat_description": "分析失败",
            "recommended_actions": [],
            "confidence_score": 0.0,
            "key_indicators": [],
            "severity_factors": []
        }
    
    def _validate_analysis_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
        """验证和标准化分析结果"""
        validated = {
            "threat_detected": bool(result.get("threat_detected", False)),
            "threat_types": result.get("threat_types", []),
            "threat_level": result.get("threat_level", "low"),
            "threat_score": float(result.get("threat_score", 0)),
            "threat_description": result.get("threat_description", ""),
            "recommended_actions": result.get("recommended_actions", []),
            "confidence_score": float(result.get("confidence_score", 0)),
            "key_indicators": result.get("key_indicators", []),
            "severity_factors": result.get("severity_factors", [])
        }
        
        # 确保威胁分数在合理范围内
        validated["threat_score"] = max(0, min(10, validated["threat_score"]))
        validated["confidence_score"] = max(0, min(1, validated["confidence_score"]))
        
        # 确保威胁等级有效
        if validated["threat_level"] not in ["low", "medium", "high", "critical"]:
            if validated["threat_score"] >= 9:
                validated["threat_level"] = "critical"
            elif validated["threat_score"] >= 7:
                validated["threat_level"] = "high"
            elif validated["threat_score"] >= 4:
                validated["threat_level"] = "medium"
            else:
                validated["threat_level"] = "low"
        
        return validated


class ThreatAnalysisSystem:
    """威胁分析系统主类"""
    
    def __init__(self, deepseek_api_key: str, db_path: str = "enterprise_analysis.db"):
        """
        初始化威胁分析系统
        
        Args:
            deepseek_api_key: DeepSeek API密钥
            db_path: 数据库文件路径
        """
        self.deepseek_api_key = deepseek_api_key
        self.db_manager = ThreatAnalysisDatabase(db_path)
        self.threat_analyzer = DeepSeekThreatAnalyzer(deepseek_api_key)
    
    async def analyze_session_threats(self, original_session_id: str) -> str:
        """
        分析指定会话的所有AI响应中的威胁
        
        Args:
            original_session_id: 原始分析会话ID
            
        Returns:
            analysis_session_id: 威胁分析会话ID
        """
        # 获取原始分析数据
        analysis_data = self.db_manager.get_analysis_data(original_session_id)
        
        if not analysis_data:
            raise ValueError(f"找不到会话数据: {original_session_id}")
        
        enterprise_name = analysis_data[0]["enterprise_name"]
        print(f"🔍 开始威胁分析: {enterprise_name} (会话: {original_session_id})")
        
        # 创建威胁分析会话
        analysis_session_id = self.db_manager.create_threat_analysis_session(
            original_session_id, enterprise_name
        )
        
        try:
            threats_detected = 0
            threat_scores = []
            highest_threat_level = "low"
            
            total_responses = len(analysis_data)
            print(f"📊 准备分析 {total_responses} 个AI响应")
            
            for i, data in enumerate(analysis_data, 1):
                print(f"🤖 分析响应 {i}/{total_responses}: {data['ai_provider']}")
                
                # 使用DeepSeek分析威胁
                threat_analysis = await self.threat_analyzer.analyze_threat(
                    question=data["question_text"],
                    ai_response=data["response_text"],
                    ai_provider=data["ai_provider"],
                    enterprise_name=enterprise_name
                )
                
                # 创建威胁分析结果
                threat_types = [ThreatType(t) for t in threat_analysis["threat_types"] 
                              if t in [tt.value for tt in ThreatType]]
                
                threat_level = ThreatLevel(threat_analysis["threat_level"])
                
                result = ThreatAnalysisResult(
                    session_id=original_session_id,
                    question_id=data["question_id"],
                    question_text=data["question_text"],
                    ai_provider=data["ai_provider"],
                    ai_response=data["response_text"],
                    threat_detected=threat_analysis["threat_detected"],
                    threat_types=threat_types,
                    threat_level=threat_level,
                    threat_score=threat_analysis["threat_score"],
                    threat_description=threat_analysis["threat_description"],
                    recommended_actions=threat_analysis["recommended_actions"],
                    confidence_score=threat_analysis["confidence_score"],
                    analysis_details=threat_analysis,
                    analyzed_at=datetime.now()
                )
                
                # 保存威胁分析结果
                self.db_manager.save_threat_analysis_result(result)
                
                # 统计信息
                if result.threat_detected:
                    threats_detected += 1
                    threat_scores.append(result.threat_score)
                    
                    # 更新最高威胁等级
                    level_priority = {"low": 1, "medium": 2, "high": 3, "critical": 4}
                    if level_priority.get(result.threat_level.value, 0) > level_priority.get(highest_threat_level, 0):
                        highest_threat_level = result.threat_level.value
                    
                    print(f"   ⚠️ 发现威胁: {result.threat_level.value.upper()} "
                          f"(评分: {result.threat_score:.1f})")
                else:
                    print(f"   ✅ 无威胁检测")
            
            # 计算平均威胁分数
            avg_threat_score = sum(threat_scores) / len(threat_scores) if threat_scores else 0
            
            # 更新威胁分析会话
            self.db_manager.update_threat_analysis_session(
                analysis_session_id=analysis_session_id,
                total_responses=total_responses,
                threats_detected=threats_detected,
                avg_threat_score=avg_threat_score,
                highest_threat_level=highest_threat_level if threats_detected > 0 else "low",
                status='completed'
            )
            
            print(f"🎉 威胁分析完成！")
            print(f"📈 总计: {total_responses} 个响应, {threats_detected} 个威胁")
            print(f"🔥 最高威胁等级: {str(highest_threat_level).upper()}")
            if avg_threat_score > 0:
                print(f"📊 平均威胁评分: {avg_threat_score:.1f}/10")
            
            return analysis_session_id
            
        except Exception as e:
            print(f"❌ 威胁分析过程中发生错误: {e}")
            self.db_manager.update_threat_analysis_session(
                analysis_session_id, status='error'
            )
            raise
    
    def print_threat_summary(self, analysis_session_id: str):
        """打印威胁分析摘要"""
        summary = self.db_manager.get_threat_summary(analysis_session_id)
        
        if not summary:
            print("❌ 找不到威胁分析结果")
            return
        
        print(f"\n{'='*80}")
        print(f"🚨 威胁分析报告")
        print(f"{'='*80}")
        print(f"🏢 企业名称: {summary['enterprise_name']}")
        print(f"🆔 分析会话ID: {summary['analysis_session_id']}")
        print(f"📅 分析时间: {summary['analysis_started_at']}")
        print(f"📊 总响应数: {summary['total_responses']}")
        print(f"⚠️ 威胁数量: {summary['threats_detected']}")
        print(f"🔥 最高威胁等级: {str(summary['highest_threat_level']).upper()}")
        
        if summary['avg_threat_score'] > 0:
            print(f"📈 平均威胁评分: {summary['avg_threat_score']:.1f}/10")
        
        # 威胁等级分布
        print(f"\n📊 威胁等级分布:")
        print("-" * 60)
        level_distribution = summary['threat_level_distribution']
        for level, count in level_distribution.items():
            if count > 0:
                print(f"  {str(level).upper():8} | {count:3} 个")
        
        # 威胁类型统计
        if summary['most_common_threat_types']:
            print(f"\n🏷️ 威胁类型统计:")
            print("-" * 60)
            sorted_types = sorted(summary['most_common_threat_types'].items(), 
                                key=lambda x: x[1], reverse=True)
            for threat_type, count in sorted_types[:5]:
                print(f"  {threat_type:20} | {count:3} 次")
        
        # 高风险威胁详情
        high_risk_threats = [t for t in summary['threat_details'] 
                           if str(t['level']).lower() in ['high', 'critical']]
        
        if high_risk_threats:
            print(f"\n🚨 高风险威胁详情:")
            print("-" * 60)
            for i, threat in enumerate(high_risk_threats[:3], 1):
                print(f"\n{i}. {str(threat['level']).upper()} 风险 (评分: {threat['score']:.1f})")
                print(f"   威胁类型: {', '.join(threat['types'])}")
                print(f"   AI来源: {threat['ai_provider']}")
                print(f"   问题: {threat['question'][:100]}...")
                print(f"   描述: {threat['description']}")
            
            if len(high_risk_threats) > 3:
                print(f"\n   ... 还有 {len(high_risk_threats) - 3} 个高风险威胁")
    
    def export_threat_report(self, analysis_session_id: str, format: str = "json") -> str:
        """导出威胁分析报告"""
        summary = self.db_manager.get_threat_summary(analysis_session_id)
        
        if format.lower() == "json":
            return json.dumps(summary, ensure_ascii=False, indent=2)
        elif format.lower() == "txt":
            lines = [
                f"企业威胁分析报告",
                f"=" * 50,
                f"企业名称: {summary['enterprise_name']}",
                f"分析时间: {summary['analysis_started_at']}",
                f"总响应数: {summary['total_responses']}",
                f"威胁数量: {summary['threats_detected']}",
                f"最高威胁等级: {str(summary['highest_threat_level']).upper()}",
                f"平均威胁评分: {summary['avg_threat_score']:.1f}/10",
                "",
                "威胁详情:",
                "-" * 30
            ]
            
            for i, threat in enumerate(summary['threat_details'], 1):
                lines.append(f"{i}. {str(threat['level']).upper()} 风险 (评分: {threat['score']:.1f})")
                lines.append(f"   类型: {', '.join(threat['types'])}")
                lines.append(f"   来源: {threat['ai_provider']}")
                lines.append(f"   问题: {threat['question']}")
                lines.append(f"   描述: {threat['description']}")
                lines.append("")
            
            return "\n".join(lines)
        else:
            return str(summary)


# 便捷函数
def create_threat_analysis_system(deepseek_api_key: str, 
                                db_path: str = "enterprise_analysis.db") -> ThreatAnalysisSystem:
    """创建威胁分析系统实例"""
    return ThreatAnalysisSystem(deepseek_api_key, db_path)


if __name__ == "__main__":
    print("🚨 威胁分析系统已加载完成！")
    print("💡 使用说明:")
    print("   1. 创建系统: system = create_threat_analysis_system(deepseek_api_key)")
    print("   2. 分析威胁: await system.analyze_session_threats(session_id)")
    print("   3. 查看报告: system.print_threat_summary(analysis_session_id)")
    print("   4. 威胁数据存储在enterprise_analysis.db的threat_analysis表中") 